module("tri",package.seeall)
env={}
envtrilist={}
tris={}
setenv=function(envname,envval)
	if envname then
		if env[envname] then
			if envval==nil then envval="$"..envname.."$" end
			if envval~=env[envname] then
				env[envname]=envval
				if envtrilist[envname] then
					local i,v
					for i,v in pairs(envtrilist[envname]) do
						settritext(i,string.gsub(tris[envname]["text"],"%$"..envname.."%$",envval))
					end
				end
			end
		end
	end
end


tritextreplaceenv=function(str)
	local val=string.gsub(str,"%$(%w+)%$",env)
	return val
end
addenv=function(envname)
	if envname then
		env[envname]="$"..envname.."$"
	end
end

loadtri=function(triname)
	returnval=nil
	if triname then
		if tris[triname] then
			tris[triname]["options"]=tris[triname]["options"] or {}
			local flag=trigger_flag.Replace+trigger_flag.Temporary+trigger_flag.RegularExpression
			if tris[triname]["options"]["omit"]==true then flag=flag+trigger_flag.OmitFromOutput end
			if tris[triname]["options"]["oneshot"]==true then flag=flag+trigger_flag.OneShot end
			if tris[triname]["options"]["enabled"]==true or defaulttrigroups[tris[triname].group] then flag=flag+trigger_flag.Enabled end
			local color=tris[triname]["options"]["color"] or -1
			returnval=AddTrigger(triname,tritextreplaceenv(tris[triname].text),"",flag,color,0,"",tris[triname].func)
			SetTriggerOption(triname,"group",tris[triname].group)
			settrioptions(triname,tris[triname]["options"])
			local i,v
			for i,v in pairs(tris[triname].envs or {}) do
				envtrilist[i]=envtrilist[i] or {}
				envtrilist[i][triname]=true
			end
		end
	end
	return returnval
end

unloadtri=function(triname)
	local i,v
	for i,v in pairs(tris[triname].envs or {}) do
		envtrilist[i]=envtrilist[i] or {}
		envtrilist[i][triname]=nil
	end
	DeleteTrigger(triname)
end

newtri=function(trid)
  newtri_default={name="",text="",group="",func=nil,options={},autoload=true}
  if trid.name then
    tris[trid.name]=misc.extend(trid,newtri_default)
    tris[trid.name].envs=findenvsfromtext(trid.text)
    if tris[trid.name].autoload then return (loadtri(trid.name)) end
  end
end
findenvsfromtext=function(str)
	local foundenvs={}
	local ienv
	for ienv in string.gmatch (str, "%$(%w+)%$") do
		if env[ienv]~=nil then foundenvs[ienv]=true end
	end
	return foundenvs
end
settrioptions=function(triname,trioptions)
end

settritext=function(triname,text)
	return SetTriggerOption (triname,"match",text) 
end
